//
//  UIImageView+PhotoBrowser.swift
//  RNAsmanMaster
//
//  Created by 李旭峰 on 7/22/19.
//  Copyright © 2019 Facebook. All rights reserved.
//

import Foundation
import AVFoundation
import MobileCoreServices
fileprivate var kVideoThumbnailBlock:Void?
fileprivate var kVideoThumbnailUrl:Void?
extension UIImageView {
  fileprivate var videoThumbnailBlock:((_ image:UIImage?,_ url:URL?)->())? {
    set{
      objc_setAssociatedObject(self, &kVideoThumbnailBlock, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
    }
    get{
      return objc_getAssociatedObject(self, &kVideoThumbnailBlock) as? ((_ image:UIImage?,_ url:URL?)->())
    }
  }
  fileprivate var videoThumbnailUrl:URL? {
    set {
      objc_setAssociatedObject(self, &kVideoThumbnailUrl, newValue, .OBJC_ASSOCIATION_COPY_NONATOMIC)
    }
    get {
      return objc_getAssociatedObject(self, &kVideoThumbnailUrl) as? URL
    }
  }
  func sd_setVideoThumbnail(with url:URL?,_ block:@escaping (_ image:UIImage?,_ url:URL?)->()){
    self.videoThumbnailUrl = url
    self.videoThumbnailBlock = block
  }
  fileprivate func getImage(){
    DispatchQueue.global().async {
      guard let tempImageUrl = self.videoThumbnailUrl else {
        DispatchQueue.main.async {
          self.videoThumbnailBlock?(nil,nil)
        }
        return
      }
      let videoUrl = tempImageUrl
      let avAsset = AVURLAsset(url: videoUrl)
      let generator = AVAssetImageGenerator(asset: avAsset)
      generator.appliesPreferredTrackTransform = true
      let time = CMTime(seconds: 0.0, preferredTimescale: 600)
      var actualTime = CMTime(value: 0, timescale: 0)
      let imageRef = try! generator.copyCGImage(at: time, actualTime: &actualTime)
      let frameImg = UIImage(cgImage: imageRef)
      DispatchQueue.main.async {
        self.videoThumbnailBlock?(frameImg,videoUrl)
      }
    }
  }
}
